<style scoped>
.doclist {
  /* padding-left: 20px;
        padding-right: 20px;
        margin-bottom: 50px; */
}

.shark {
  /* padding: 0 30px; */
}

.fast {
  font-size: 20px;
  color: #f39312;
  letter-spacing: 1px;
}

.doclist .main .ivu-select,
.main .ivu-input {
  border-radius: 0 2px 2px 0;
}

.doclist .common-box-body {
  padding-top: 24px;
}
.doclist .fixed-bottom {
  padding-left: 30px;
  padding-right: 40px;
  height: 80px;
  line-height: normal !important;
  position: fixed;
  left: 210px;
  right: 0;
  bottom: 0;
  z-index: 999;
  text-align: center;
  background-color: rgb(255, 255, 255);
  box-shadow: 0px 0px 9px 0px rgba(0, 0, 0, 0.28);
}
.sidehide {
  left: 75px;
}
.detail{
    margin-top: 20px ;
    margin-bottom: 15px;
}
</style>
<style>
.doclist
  .common-box-body
  .ivu-select-single
  .ivu-select-selection
  .ivu-select-placeholder,
.common-box-body
  .ivu-select-single
  .ivu-select-selection
  .ivu-select-selected-value {
  padding-right: 0px;
}

.doclist .ivu-tabs.ivu-tabs-card > .ivu-tabs-bar .ivu-tabs-tab {
  color: #2d8cf0;
  border-color: transparent;
  background-color: #fff;
}

.doclist .ivu-tabs.ivu-tabs-card > .ivu-tabs-bar .ivu-tabs-tab-active {
  color: #808080;
  border: 1px solid #dddee1;
  border-bottom: 0;
}
.doclist button.ivu-btn {
  border-radius: 2px !important;
}
</style>


<template>
    <div class="doclist">
        <product-title></product-title>
        <div class="shark"  style="padding:0 30px;">
            <div class="fast">快速搜索</div>
            <div class="common-box-body">
                <Form >
                    <Row>
                        <Col :md="24" :lg="11">
                            <Form-item label="分支机构">
                              <Select  filterable   placeholder="请选择分支机构" v-model="formdata.yun_org_mid" :transfer=true>
                                  <Option value="">全部</Option>  
                                  <Option v-for="item in orglist" :value="item.id" :key="item.id">{{item.shortn}}</Option>                                                                                                                                       
                              </Select>
                            </Form-item>
                        </Col>
                        <!-- <Col :md="24" :lg="11">
                            <FormItem>
                                <Input placeholder="请输入帐号名或登录名" v-model="formdata.yun_name"></Input>
                            </FormItem>
                        </Col> -->
                        <!-- <Col :xs="24" :sm="24" :md="6" :lg="6"  class="same shen">
                            <FormItem prop="reg_dateall" label="创建时间">
                                    <DatePicker  type="date"   v-model="formdata.create_timed" @on-change="datachange($event,formdata,'create_time')"  placeholder="请选择" :transfer=true placement="bottom"></DatePicker>  
                            </FormItem>
                        </Col> -->
                        <Col :md="24" :lg="2">
                            <Button size="large" class="fr" type="primary" icon="ios-search" @click="search">搜索</Button>
                        </Col>
                    </Row>
                    <div style="border-bottom:1px solid #BEBEBE;"></div>
                </Form>
            </div>
            <div class="detail">
                <Row>
                  <Col span="24" class="table-action" >
                      <Button type="warning" size="large" class="fr" icon="plus" @click="addAccount">新增帐号</Button>
                  </Col>
                </Row>             
                <div class="clearfix">
                    <div class="table-theme highlight_table">
                        <Table :loading="tableloading"  ref="currentRowTable" @on-current-change="tableCurrentChange($event)" size="large" stripe highlight-row border :columns="columns1" :data="policylist" class=""></Table>
                    </div>                        
                </div>
            </div>
            <div :class="slidetoggle?'fixed-bottom':'fixed-bottom sidehide' ">
                <Row class="pro-pagesize">
                    <Col :md="24" :lg="16">
                        <Button type="error" :disabled="tableaction" size="large" class="fl mr10 " @click="remove">删除</Button>
                        <Button type="info" :disabled="tableaction" size="large" class="fl mr10" @click="modalTrue">编辑</Button>
                    </Col>
                    <Col :md="24" :lg="8" class="tRight">
                        <Page :total="detailTotal"  ref='pages' :current="currentpage" show-total show-sizer :page-size="pagesize" @on-change="pageChange" @on-page-size-change="pageSizeChange" placement="top" class="page"></Page>
                    </Col>
                </Row>
            </div>
        </div>
        <Modal v-model="showAddModal" ok-text="提交" :mask-closable='closeable' width="600" title="编辑账号信息" @on-ok="add" @on-cancel="cancel" :loading="loading" class-name="common-box-body showAddModal">
            <Row>
                <Col>
                    <Form :model="org" ref="org" :rules="ruleValidate"  >
                        <Form-item label="分支机构" prop="name" required>
                            <Select  filterable :disabled="org_disabled"  placeholder="请选择分支机构" v-model="org.org_mid" :transfer=true>                                
                                <Option v-for="item in orglist" :value="item.id" :key="item.id">{{item.shortn}}</Option>                                                                                                                                       
                            </Select>
                        </Form-item>
                        <Form-item label="账号名" prop="name" required>
                            <Input v-model="org.name" placeholder="请输入账号登录名"></Input>
                        </Form-item>
                        <Form-item label="登录名" prop="login_name" required >
                            <Input v-model="org.login_name" placeholder="请输入账号登录名"></Input>
                        </Form-item>
                        <Form-item label="登录密码" prop="pwd" required>
                            <Input v-model="org.pwd" type="password" placeholder="请输入登录密码,至少保证8位"></Input>
                        </Form-item>
                        <Form-item label="确认密码" prop="pwd_two" required>
                            <Input v-model="org.pwd_two" type="password" placeholder="请再次输入登录密码,密码必须一致"></Input>
                        </Form-item>
                        <Form-item label="策略组" prop="permission" required>
                            <Select v-model="org.permission" placeholder="选择策略组">
                                <Option :value="item._id" v-for="item in permission_list" :key="item._id">{{item.name}}</Option>
        
                            </Select>
                        </Form-item>
                        <!-- <Form-item label="限额" prop="quota" >
                            <Input v-model="org.quota" placeholder="请输入机构限额为纯数字且最多10位数字"></Input>
                        </Form-item> -->
                    </Form>
                </Col>
            </Row>
        </Modal>
    </div>
</template>

<script>
import productTitle from "../../components/productTitle";
import { getListByName } from '../../api/yun_org'
import {account_list,delete_account,get_account,set_yun_account} from "../../api/org";
import { yunUserCreate , yunUserGetDetail , yunUserUpdate , yunUserGetList , yunUserDel } from '../../api/yun_user'
import { PermissionGetAll } from '../../api/yun_permission'
export default {
  data() {
    const validatePass = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("请输入密码"));
      } else {
        if (this.org.pwd_two !== "") {
          // 对第二个密码框单独验证
          this.$refs.org.validateField("pwd_two");
        }
        callback();
      }
    };
    const validatePassCheck = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("请再次输入密码"));
      } else if (value !== this.org.pwd) {
        callback(new Error("两次输入的密码不匹配!"));
      } else {
        callback();
      }
    };
    return {
      tableloading:true,
      org_disabled:false,
      permission_list:[],
      p: 1, //对页面页数的定义-->初始化
      pagesize: 10, //对页面的定义,出事定义10条数据
      detailTotal: 0,
      currentpage:1,
      // tableloading:true,//加载动作
      showAddModal: false, //点击设置,弹出模态框
      closeable: false, //shif按ese按钮退出
      loading: true, //模态框家在状态提交确定
      tableaction: true, //点击具体数据,改变联动编辑删除高亮状态
      proList: [],
      orglist:[],
      formdata: {
        p: 1, //对页面页数的定义-->初始化
        pagesize: 10, //对页面的定义,出事定义10条数据
        yun_org_mid:'',
      },
      policylist: [],
      columns1: [
        {
          title: "机构简称",
          key: "org_name",
          align: "center"
        },
        {
          title: "机构账号",
          key: "name",
          align: "center"
        },
        {
          title: "登录名",
          key: "login_name",
          align: "center"
        },
        {
          title: "创建时间",
          key: "create_time",
          align: "center"
        },
        // {
        //   title: "限额",
        //   key: "quota",
        //   align: "center"
        // }
      ],
      org: {
        // name: "", //帐号名
        // login_name: "", //登录名
        // role_name: "", // 角色名
        // pwd: "", //密码
        // role_id: "",//角色id
        // // quota:'',//限额
        // yun_id:""pattern: /^[1-9]\d{0,9}$/,max: 11,
      },
      ruleValidate: {
        name: [{ required: true, message: "帐号名不能为空", trigger: "blur" }],
        pwd: [{required: true,validator: validatePass, trigger: "blur" }],
        pwd_two: [{required: true,validator: validatePassCheck, trigger: "blur" }],
        login_name: [
          { required: true, message: "登录名不能为空", trigger: "blur" }
        ],
        permission:[
            { required: true, message: '策略组不能为为空', trigger: 'blur,change' },
        ],
        quota: [{ required: true, message: '限额不能为空且最大只能输入10位数字',}]
      }
    };
  },
  components: {
    productTitle
  },
  created() {},
  mounted () {
    this.getList();
    this.orglistinit();
    this.PermissionGet();
  },
  methods: {
    PermissionGet(){               
        new Promise((resolve, reject) => {
            PermissionGetAll().then(response => {
                if (response.data.err == 0) {
                    this.permission_list = response.data.data
                } else {
                    
                }
                resolve();
            }).catch(error => {
                reject(error);
            });
        });
    },
    orglistinit(){
          new Promise((resolve, reject) => {
          let _params = {
              name:''
          }
          getListByName(_params).then(response => {
                  console.log(response.data)
                  if (response.data.err == 0) {               
                      this.orglist = response.data.data;
                  } else {
                      this.$Message.error(response.data.info);
                  }
                  resolve();
              }).catch(error => {
                  reject(error);
              });
          });
    },
    addAccount(){
      this.$refs["org"].resetFields();
      delete this.org.mongo_id
      delete this.org.quota
      delete this.org.id
      this.org = {}
      this.org_disabled = false
      this.showAddModal = true      
    },
    //时间转换
      datachange(date,obj,param){
          obj[param] = date
      },
    // 页码改变
    pageChange(page) {
      this.p = page;
      this.formdata.p = page;
      this.getList();
    },
    // 每页条数改变
    pageSizeChange(pagesize) {
      this.pagesize = pagesize;
      this.formdata.pagesize = pagesize;
      this.getList();
    },
    // 点击搜索,进行数据搜索
    search() {
      this.tableloading = true
      this.formdata.p=1;
      new Promise((resolve, reject) => {
        yunUserGetList(this.formdata)
          .then(response => {
            console.log(response.data,"")
            if (response.data.err == 0) {
              this.$Message.success(response.data.info);
              this.policylist = response.data.data.list;
              this.detailTotal = response.data.data.total;
              this.$refs['pages'].currentPage = 1 
            } else {
              this.$Message.error(response.data.info);
              this.policylist=[];
              this.detailTotal=0;
            }
            resolve();
            this.tableloading = false
          })
          .catch(error => {
            reject(error);
            this.tableloading = false
          });
      });
    },
    //获取页面信息getList
    getList() {
      let params = {
        p: this.p,
        pagesize: this.pagesize
      };
      new Promise((resolve, reject) => {
        yunUserGetList(params)
          .then(response => {
            console.log(response.data, "查询列表");
            if (response.data.err == 0) {
              console.log(response.data.data.data,"/.....")
              this.policylist = response.data.data.list;
              this.detailTotal = response.data.data.total;
            } else if(response.data.err == 1400){
              // 后台返回数据小bug  当没有数据的时候response.data.data
              this.$Message.error(response.data.info);
              this.policylist = response.data.data
            }else{
              this.$Message.error(response.data.info);
            }
            this.tableloading = false
            resolve();
          })
          .catch(error => {
            reject(error);
            this.tableloading = false
          });
      });
    },
    //选中当前行数据
    tableCurrentChange(currentRow, oldCurrentRow) {
      // tableaction状态高亮 current获取具体行的id
      this.tableaction = false;
      this.current = currentRow;
      console.log(this.current,"信息");
      this.current.mongo_id = currentRow.mongo_id;
    },
    // 点击删除执行删除选中的table操作
    remove() {
      this.$Modal.confirm({
        title: "提示",
        content: "是否要解除该机构绑定的所有账号信息?请谨慎操作!",
        onOk: () => {
          var _param = {
            yun_id: this.current.id,
          };
          console.log(_param,"id")
          new Promise((resolve, reject) => {
            yunUserDel(_param)
              .then(response => {
                console.log(response.data, "查看状态");
                if (response.data.err == 0) {
                  this.$Message.success(response.data.info);
                  // this.getList();
                  location.reload();
                } else {
                  this.$Message.error(response.data.info);
                }
                resolve();
              })
              .catch(error => {
                reject(error);
              });
          });
        }
      });
    },
    // 点击设置显示模态框
    modalTrue() {
      this.showAddModal = true; 
      this.org_disabled = true
      var _param = {
          yun_id: this.current.id
        };
       new Promise((resolve, reject) => {
          yunUserGetDetail(_param)
            .then(response => {
              console.log(response, ".......");
              if (response.data.err == 0) {
                this.org = response.data.data;
                this.org.pwd_two = response.data.data.pwd;
                this.org.org_mid = this.current.mongo_id
                this.org.yun_id = this.current.id
              }else{
                this.$Message.error(response.data.info);
              }
              resolve();
            })
            .catch(error => {
              reject(error);
            });
        });
    },
    add() {
      this.$refs["org"].validate(valid => {
        if (valid) {
            
            // this.org.mongo_id = this.current.mongo_id;
            console.log(this.org,"提交表单")
            if(this.org.yun_id){
              this.org.type = 2
              new Promise((resolve, reject) => {
                  yunUserUpdate(this.org).then(response => {
                      if (response.data.err == 0) {
                          this.showAddModal = false;
                          this.$Message.success(response.data.info);
                          this.$refs["org"].resetFields();
                          this.getList()
                      } else {
                          this.$Message.error(response.data.info);
                          this.loading = false;
                          this.showAddModal = true;
                      }
                      resolve();
                  }).catch(error => {
                      reject(error);
                  });
              });
            }else{
              this.org.type = 2
              new Promise((resolve, reject) => {
                  yunUserCreate(this.org).then(response => {
                      if (response.data.err == 0) {
                          this.showAddModal = false;
                          this.$Message.success(response.data.info);
                          this.$refs["org"].resetFields();
                          this.getList()
                      } else {
                          this.$Message.error(response.data.info);
                          this.loading = false;
                          this.showAddModal = true;
                      }
                      resolve();
                  }).catch(error => {
                      reject(error);
                  });
              });
            }
            
        } else {
          // 通过loading来阻止modal隐藏，然后手动修改loading来充值确定按钮
          setTimeout(() => {
            this.loading = false;
            this.$nextTick(() => {
              this.loading = true;
              this.showAddModal = true;   
            });
          }, 1000);
        }
      });
    },
    cancel() {
      this.$refs["org"].resetFields();
    }
  },
  computed: {
    slidetoggle() {
      return this.$store.state.sildeshow;
    }
  },
};
</script>